<template>
  <div
    style="flex: 0.8; display: flex; justify-content: right; align-items: center; padding: 0 40px"
  >
    <a-flex gap="small" :align="'center'" justify="end">
      <a-tooltip title="返回首页">
        <a-button @click="router.push('/')" size="large" shape="circle" :icon="h(HomeOutlined)" />
      </a-tooltip>
      <a-avatar
        :src="userAvatar || 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png'"
        :size="40"
      >
        <template #icon><UserOutlined /></template>
      </a-avatar>
      <a-dropdown arrow>
        <a @click.prevent> {{ username }} </a>
        <template #overlay>
          <a-menu>
            <a-menu-item @click="goToProfile">
              <user-outlined />
              <span>个人中心</span>
            </a-menu-item>
            <a-menu-item @click="logout">
              <logout-outlined />
              <span>退出登录</span>
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </a-flex>
  </div>
</template>

<script setup>
import { h, computed, onMounted } from 'vue'
import { UserOutlined, HomeOutlined, LogoutOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { message } from 'ant-design-vue'

// 变量定义
const router = useRouter()
const userStore = useUserStore()

// 用户信息计算属性
const username = computed(() => userStore.userInfo.username || '管理员')
const userAvatar = computed(() => userStore.userInfo.avatar)

// 退出登录
const logout = async () => {
  try {
    await userStore.logout()
    message.success('退出登录成功')
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
    message.error('退出登录失败')
  }
}

// 跳转到个人中心
const goToProfile = () => {
  // 管理员使用管理后台内嵌的个人中心页面
  router.push('/admin/profile')
}

// 组件挂载时获取最新用户信息
onMounted(async () => {
  if (userStore.isLoggedIn) {
    try {
      await userStore.fetchUserInfo()
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }
})
</script>

<style lang="scss" scoped></style>
